package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.base.BaseEntity;
import com.ruoyi.common.constant.CacheKeyConstants;
import com.ruoyi.common.constant.ResultConstants;
import com.ruoyi.common.enums.AmountType;
import com.ruoyi.common.enums.TxnType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.support.Convert;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.system.domain.WdyTxnHistory;
import com.ruoyi.system.domain.WdyUser;
import com.ruoyi.system.domain.WdyVcBuyOrder;
import com.ruoyi.system.mapper.WdyVcBuyOrderMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.IWdyTxnHistoryService;
import com.ruoyi.system.service.IWdyUserService;
import com.ruoyi.system.service.IWdyVcBuyOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * vc购买订单 服务层实现
 * 
 * @author ruoyi
 * @date 2019-12-16
 */
@Service
public class WdyVcBuyOrderServiceImpl extends ServiceImpl<WdyVcBuyOrderMapper, WdyVcBuyOrder> implements IWdyVcBuyOrderService
{
	@Autowired
	private ISysConfigService sysConfigService;
	@Autowired
	private IWdyUserService wdyUserService;

	@Autowired
	private IWdyTxnHistoryService wdyTxnHistoryService;
	/**
     * 查询vc购买订单信息
     * 
     * @param id vc购买订单ID
     * @return vc购买订单信息
     */
    @Override
	public WdyVcBuyOrder selectWdyVcBuyOrderById(Long id)
	{
	    return baseMapper.selectWdyVcBuyOrderById(id);
	}
	
	/**
     * 查询vc购买订单列表
     * 
     * @param wdyVcBuyOrder vc购买订单信息
     * @return vc购买订单集合
     */
	@Override
	public List<WdyVcBuyOrder> selectWdyVcBuyOrderList(WdyVcBuyOrder wdyVcBuyOrder)
	{
	    return baseMapper.selectWdyVcBuyOrderList(wdyVcBuyOrder);
	}
	
    /**
     * 新增vc购买订单
     * 
     * @param wdyVcBuyOrder vc购买订单信息
     * @return 结果
     */
	@Override
	public int insertWdyVcBuyOrder(WdyVcBuyOrder wdyVcBuyOrder)
	{
	    return baseMapper.insertWdyVcBuyOrder(wdyVcBuyOrder);
	}
	
	/**
     * 修改vc购买订单
     * 
     * @param wdyVcBuyOrder vc购买订单信息
     * @return 结果
     */
	@Override
	public int updateWdyVcBuyOrder(WdyVcBuyOrder wdyVcBuyOrder)
	{
	    return baseMapper.updateWdyVcBuyOrder(wdyVcBuyOrder);
	}

	/**
     * 删除vc购买订单对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteWdyVcBuyOrderByIds(String ids)
	{
		return baseMapper.deleteWdyVcBuyOrderByIds(Convert.toStrArray(ids));
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void buyVc(WdyVcBuyOrder order) {
		if(order.getAmount() == null) {
			throw new BusinessException(ResultConstants.FI1000, "amount" + MessageUtils.message("not.null"));
		}
		BigDecimal amount = BigDecimalUtil.getP2BigDecimal(order.getAmount());
		if(amount.compareTo(BigDecimal.ZERO) <= 0) {
			throw new BusinessException(ResultConstants.FI1000, "amount" + MessageUtils.message("param.error"));
		}

		AmountType amountType = AmountType.getByCode(order.getAmountType());
		if(amountType == null) {
			throw new BusinessException(ResultConstants.FI1000, "amountType" + MessageUtils.message("param.error"));
		}

		BigDecimal buyMinAmount = new BigDecimal(sysConfigService.selectConfigByKey("buy_vc_min_amount"));

		if(amount.compareTo(buyMinAmount) < 0) {
			throw new BusinessException(ResultConstants.FI1000, String.format("最低购买金额为%s%s", buyMinAmount, amountType));
		}

		order.setAmount(amount);

		QueryWrapper<WdyUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("user_id", order.getUserId());
		queryWrapper.eq("del_flag", BaseEntity.NOT_DELETED);
		WdyUser user = wdyUserService.getOne(queryWrapper);

		BigDecimal totalCnn = user.getCnnAmount().add(user.getCnnWithdrawAmount());
		if(totalCnn.compareTo(amount) < 0) {
			throw new BusinessException(ResultConstants.FI1000, "cnn余额不足");
		}


		BigDecimal vcRatio = new BigDecimal(sysConfigService.selectConfigByKey(CacheKeyConstants.VC_RATIO));
		BigDecimal vcPrice = BigDecimalUtil.getP2BigDecimal(BigDecimalUtil.divide(1, vcRatio));
		BigDecimal vcAmount = BigDecimalUtil.getP2BigDecimal(BigDecimalUtil.multiply(amount, vcRatio));

		WdyUser updateUser = new WdyUser();
		if(user.getCnnAmount().compareTo(amount) >= 0) {
			updateUser.setCnnAmount(BigDecimalUtil.subtract(user.getCnnAmount(), amount));
		} else {
			updateUser.setCnnAmount(BigDecimal.ZERO);
			updateUser.setCnnWithdrawAmount(BigDecimalUtil.subtract(user.getCnnWithdrawAmount(), amount.subtract(user.getCnnAmount())));
		}
		updateUser.setVcAmount(BigDecimalUtil.add(user.getVcAmount(), vcAmount));
		updateUser.setVersion(user.getVersion());
		if (!wdyUserService.update(updateUser, queryWrapper)) {
			throw new BusinessException(ResultConstants.EX9110, "系统繁忙，请稍后重试");
		}

		order.setVcAmount(vcAmount);
		order.setPrice(vcPrice);
		order.setAmountType(AmountType.CNN.getCode());
		this.save(order);

		WdyTxnHistory txnHistory = new WdyTxnHistory();
		txnHistory.setUserId(order.getUserId());
		txnHistory.setTxnId(String.valueOf(order.getId()));
		txnHistory.setTxnAmount(BigDecimalUtil.subtract(0, amount));
		txnHistory.setTxnType(TxnType.BUY_VC_CNN.getCode());
		txnHistory.setAmountType(TxnType.BUY_VC_CNN.getAmountType().getCode());
		txnHistory.setTxnDesc(TxnType.BUY_VC_CNN.getName());
		wdyTxnHistoryService.save(txnHistory);

		txnHistory = new WdyTxnHistory();
		txnHistory.setUserId(order.getUserId());
		txnHistory.setTxnId(String.valueOf(order.getId()));
		txnHistory.setTxnAmount(vcAmount);
		txnHistory.setTxnType(TxnType.BUY_VC.getCode());
		txnHistory.setAmountType(TxnType.BUY_VC.getAmountType().getCode());
		txnHistory.setTxnDesc(TxnType.BUY_VC.getName());
		wdyTxnHistoryService.save(txnHistory);
	}

	@Override
	public Map<String, BigDecimal> getSum(WdyVcBuyOrder wdyVcBuyOrder) {
		return baseMapper.getSum(wdyVcBuyOrder);
	}
}
